package com.bupt.inklue.service;

import com.bupt.inklue.dto.UserDTO;
import com.bupt.inklue.pojo.User;
import com.bupt.inklue.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public boolean add(UserDTO userDTO) {
        User user = new User(userDTO);
        User ret = userRepository.save(user);
        return ret.getId() > 0;
    }

    public boolean delete(UserDTO userDTO) {
        User user = userRepository.findByAccount(userDTO.getAccount()).orElseThrow();
        if (userDTO.getPassword().equals(user.getPassword())) {
            userRepository.delete(user);
            return true;
        }
        return false;
    }

    public boolean edit(UserDTO userDTO) {
        User user = userRepository.findByAccount(userDTO.getAccount()).orElseThrow();
        if (userDTO.getPassword().equals(user.getPassword())) {
            User edit = new User(userDTO);
            edit.setId(user.getId());
            User ret = userRepository.save(edit);
            return ret.getId() > 0;
        }
        return false;
    }

    public UserDTO getByAccount(String account) {
        User user = userRepository.findByAccount(account).orElseThrow();
        return new UserDTO(user);
    }
}
